﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using Tesla.Service.DataContracts;
using System.IO;
using Microsoft.Practices.EnterpriseLibrary.ExceptionHandling;
using Microsoft.Practices.EnterpriseLibrary.Logging;
//using Telerik.Web.UI;
using Tesla.Util.Utilities;

namespace Tesla.Web.Pages.Administrator
{
    public partial class EmployeeSearch : PageBase
    {
        #region Private Class Level Variables
        private DataTable EmployeeTable = new DataTable("Employee");
        private EmployeeServiceDispatcher esd = new EmployeeServiceDispatcher();
        private int? EmployeeRecordCount = 0;
        #endregion

        

        protected void Page_Load(object sender, EventArgs e)
        {
            try
            {
                if (!IsPostBack)
                {
                    ViewState["_SortExp_"] = "EmployeeFirstName";
                    ViewState["_Direction_"] = SortDirection.Ascending;
                    btnDisplayAll_Click(null, null);
                }
            }
            catch (Exception ex)
            {
                bool rethrow = ExceptionPolicy.HandleException(ex, "GADN Custom Exception Policy");
                throw new GADNCustomException("Some Errors have occurred in the application.", "LearningSourcesSearch", "Page_Load");
            }
        }


        protected void btnDisplayAll_Click(object sender, EventArgs e)
        {
            try
            {
                List<BaseDC> employees = esd.DisplayAllEmployee(grdEmployees.PageSize, ref EmployeeRecordCount).ToList();
                grdEmployees.Visible = true;
                btnNext.Enabled = true;
                btnPrevious.Enabled = true;
                txtEmployeeName.Text = String.Empty;
                this.hddSearhText.Value = string.Empty;
                ViewState["CurrentpageNumber"] = 1;
                ViewState["_SortExp_"] = "EmployeeFirstName";
                ViewState["_Direction_"] = SortDirection.Ascending;

                ShowDevelopmentActivityInGrid(employees, 1);

                ViewState["TotalPages"] = CalculateTotalPages(Convert.ToDouble(EmployeeRecordCount));

                ShowFooter();

                PopulateDropDownList();
            }
            catch (Exception ex)
            {
                bool rethrow = ExceptionPolicy.HandleException(ex, "GADN Custom Exception Policy");
                throw new GADNCustomException("Some Errors have occurred in the application.", "LearningSourcesSearch", "btnDisplayAll_Click");
            }
        }

        protected void btnSearch_Click(object sender, EventArgs e)
        {
            try
            {
                this.hddSearhText.Value = txtEmployeeName.Text;
                List<BaseDC> employees = esd.SearchEmployeeByName(this.hddSearhText.Value.Replace("'", "''"), grdEmployees.PageSize, ref EmployeeRecordCount).ToList();

                grdEmployees.Visible = true;
                btnNext.Enabled = true;
                btnPrevious.Enabled = true;

                ViewState["CurrentpageNumber"] = 1;
                ViewState["_SortExp_"] = "EmployeeFirstName";
                ViewState["_Direction_"] = SortDirection.Ascending;

                ShowDevelopmentActivityInGrid(employees, 1);

                ViewState["TotalPages"] = CalculateTotalPages(Convert.ToDouble(EmployeeRecordCount));

                ShowFooter();
                PopulateDropDownList();
            }
            catch (Exception ex)
            {
                bool rethrow = ExceptionPolicy.HandleException(ex, "GADN Custom Exception Policy");
                throw new GADNCustomException("Some Errors have occurred in the application.", "LearningSourcesSearch", "btnSearch_Click");
            }
        }

        private void ShowDevelopmentActivityInGrid(List<BaseDC> employees, int employeeStart)
        {           
            if (EmployeeTable.Columns.Count == 0)
                EmployeeTable.Columns.AddRange(new DataColumn[]{
                                                     new DataColumn("EmployeeID", typeof(int)),
                                                     new DataColumn("EmployeeName", typeof(string)),
                                                     new DataColumn("EmployeeDesignation", typeof(string)),
                                                     new DataColumn("EmployeeDOB", typeof(DateTime)),
                                                     new DataColumn("EmployeeDOJ", typeof(DateTime)),
                                                     new DataColumn("EmployeeManagerName", typeof(string)),
                                                     new DataColumn("EmployeeRoleName", typeof(string))});

            foreach (BaseDC bDC in employees)
            {
                DataRow dr = EmployeeTable.NewRow();
                dr["EmployeeID"] = ((EmployeeDC)bDC).EmployeeID;
                dr["EmployeeName"] = ((EmployeeDC)bDC).EmployeeName;
                dr["EmployeeDesignation"] = ((EmployeeDC)bDC).EmployeeDesignation;
                dr["EmployeeDOB"] = ((EmployeeDC)bDC).EmployeeDOB;
                dr["EmployeeDOJ"] = ((EmployeeDC)bDC).EmployeeDOJ;
                dr["EmployeeManagerName"] = ((EmployeeDC)bDC).EmployeeManagerName;
                dr["EmployeeRoleName"] = ((EmployeeDC)bDC).EmployeeRoleName;
                //dr["EmployeeWorkdayDuration"] = ((EmployeeDC)bDC).EmployeeWorkdayDuration;
                EmployeeTable.Rows.Add(dr);
            }

            grdEmployees.DataSource = EmployeeTable;
            grdEmployees.DataBind();            
        }

        protected void ChangePage(object sender, CommandEventArgs e)
        {
            try
            {
                switch (e.CommandName)
                {
                    case "Previous":
                        ViewState["CurrentpageNumber"] = (int)ViewState["CurrentpageNumber"] - 1;
                        ddlPageNos.SelectedIndex = Convert.ToInt32(ViewState["CurrentpageNumber"]) - 1;
                        break;

                    case "Next":
                        ViewState["CurrentpageNumber"] = (int)ViewState["CurrentpageNumber"] + 1;
                        ddlPageNos.SelectedIndex = Convert.ToInt32(ViewState["CurrentpageNumber"]) - 1;
                        break;
                }
                BindData();
            }
            catch (Exception ex)
            {
                bool rethrow = ExceptionPolicy.HandleException(ex, "GADN Custom Exception Policy");
                throw new GADNCustomException("Some Errors have occurred in the application.", "LearningSourcesSearch", "ChangePage");
            }
        }

        protected void ddlPageNos_SelectedIndexChanged(object sender, EventArgs e)
        {
            try
            {
                ViewState["CurrentpageNumber"] = Convert.ToInt32(ddlPageNos.SelectedValue);
                BindData();
            }
            catch (Exception ex)
            {
                //bool rethrow = ExceptionPolicy.HandleException(ex, "GADN Custom Exception Policy");
                //throw new GADNCustomException("Some Errors have occurred in the application.", "LearningSourcesSearch", "ddlPageNos_SelectedIndexChanged");
            }
        }

        protected void OnSort(object sender, GridViewSortEventArgs e)
        {
            try
            {
                if (String.Compare(e.SortExpression, ViewState["_SortExp_"].ToString(), true) == 0)
                {
                    ViewState["_Direction_"] =
                        ((SortDirection)ViewState["_Direction_"] == SortDirection.Ascending) ? SortDirection.Descending : SortDirection.Ascending;
                }
                else
                {
                    ViewState["_Direction_"] = e.SortDirection;
                }
                ViewState["_SortExp_"] = e.SortExpression;
                BindData();
            }
            catch (Exception ex)
            {
                bool rethrow = ExceptionPolicy.HandleException(ex, "GADN Custom Exception Policy");
                throw new GADNCustomException("Some Errors have occurred in the application.", "LearningSourcesSearch", "OnSort");
            }
        }

        protected void OnRowCreated(object sender, GridViewRowEventArgs e)
        {
            try
            {
                if (e.Row.RowType == DataControlRowType.Header)
                {
                    if (String.Empty != ViewState["_SortExp_"].ToString())
                    {
                        AddSortImage(e.Row);
                    }
                }
            }
            catch (Exception ex)
            {
                bool rethrow = ExceptionPolicy.HandleException(ex, "GADN Custom Exception Policy");
                throw new GADNCustomException("Some Errors have occurred in the application.", "LearningSourcesSearch", "OnRowCreated");
            }
        }

       

        private void ShowFooter()
        {            
            if ((int)ViewState["TotalPages"] == 1 && (int)ViewState["CurrentpageNumber"] == 1)
            {
                btnPrevious.Enabled = false;
                btnNext.Enabled = false;
                btnFirst.Enabled = false;
                btnLast.Enabled = false;
            }
            else if ((int)ViewState["TotalPages"] > 1 && (int)ViewState["CurrentpageNumber"] == 1)
            {
                btnPrevious.Enabled = false;
                btnNext.Enabled = true;
                btnLast.Enabled = true;
                btnFirst.Enabled = false;
            }
            else if ((int)ViewState["TotalPages"] > 1 && (int)ViewState["CurrentpageNumber"] > 1 && (int)ViewState["CurrentpageNumber"] < (int)ViewState["TotalPages"])
            {
                btnPrevious.Enabled = true;
                btnNext.Enabled = true;
                btnFirst.Enabled = true;
                btnLast.Enabled = true;
            }
            else if ((int)ViewState["TotalPages"] < 1)
            {
                btnPrevious.Enabled = false;
                btnNext.Enabled = false;
                btnFirst.Enabled = false;
                btnLast.Enabled = false;
                ViewState["CurrentpageNumber"] = 0;
            }
            //else if 
            //else if ((int)ViewState["CurrentpageNumber"] == (int)ViewState["TotalPages"])
            //{
            //    btnPrevious.Enabled = true;
            //    btnNext.Enabled = false;
            //}
            else
            {
                btnPrevious.Enabled = true;
                btnFirst.Enabled = true;
                btnNext.Enabled = false;
                btnLast.Enabled = false;
            }
            lblPageNo.Text = "Page " + ViewState["CurrentpageNumber"].ToString() + " Of " + ViewState["TotalPages"].ToString();            
        }


        private void PopulateDropDownList()
        {
            ddlPageNos.Items.Clear();
            for (int i = 1; i <= (int)ViewState["TotalPages"]; i++)
                ddlPageNos.Items.Add(i.ToString());
           
        }

        private void BindData()
        {
            List<BaseDC> DevelopmentActivity = esd.ReadEmployeeByRowNumberRange((((int)ViewState["CurrentpageNumber"] - 1) * grdEmployees.PageSize) + 1, (int)ViewState["CurrentpageNumber"] * grdEmployees.PageSize, ViewState["_SortExp_"].ToString(),
                (SortDirection)ViewState["_Direction_"] == SortDirection.Ascending ? "ASC" : "DESC", !string.IsNullOrEmpty(this.hddSearhText.Value) ? this.hddSearhText.Value : string.Empty).ToList();

            int EmployeeCount = (((int)ViewState["CurrentpageNumber"] - 1) * grdEmployees.PageSize) + 1;
            ShowDevelopmentActivityInGrid(DevelopmentActivity, EmployeeCount);
            ShowFooter();            
        }


        private int CalculateTotalPages(double totalRows)
        {
            int totalPages = 0;
            totalPages = (int)Math.Ceiling(totalRows / grdEmployees.PageSize);
            return totalPages;
        }

        private int GetSortColumnIndex(String strCol)
        {
            foreach (DataControlField field in this.grdEmployees.Columns)
            {
                if (field.SortExpression == strCol)
                {
                    return grdEmployees.Columns.IndexOf(field);
                }
            }            
            return -1;
        }

        private void AddSortImage(GridViewRow headerRow)
        {            
            Int32 iCol = GetSortColumnIndex(ViewState["_SortExp_"].ToString());
            if (-1 == iCol)
            {
                return;
            }
            // Create the sorting image based on the sort direction.
            Image sortImage = new Image();
            if (SortDirection.Ascending == (SortDirection)ViewState["_Direction_"])
            {
                //sortImage.ImageUrl = "~/Images/down.gif";
                sortImage.ImageUrl ="~/Images/Up.png";
              //  sortImage.AlternateText = "Ascending Order";
            }
            else
            {
                //sortImage.ImageUrl = "~/Images/up.jpg";
                sortImage.ImageUrl = "~/Images/Down.png";
                //sortImage.AlternateText = "Descending Order";
            }

            // Add the image to the appropriate header cell.
            headerRow.Cells[iCol].Controls.Add(sortImage);           
        }

        protected void btnLast_Click(object sender, EventArgs e)
        {
            try
            {
                ViewState["CurrentpageNumber"] = Convert.ToInt32((int)ViewState["TotalPages"]);
                BindData();
                ddlPageNos.SelectedIndex = Convert.ToInt32(ViewState["CurrentpageNumber"]) - 1;
            }
            catch (Exception ex)
            {
                bool rethrow = ExceptionPolicy.HandleException(ex, "GADN Custom Exception Policy");
                throw new GADNCustomException("Some Errors have occurred in the application.", "LearningSourcesDetails", "btnLast_Click");
            }
        }

        protected void btnFirst_Click(object sender, EventArgs e)
        {
            try
            {
                ViewState["CurrentpageNumber"] = 1;
                BindData();
                ddlPageNos.SelectedIndex = Convert.ToInt32(ViewState["CurrentpageNumber"]) - 1;
            }
            catch (Exception ex)
            {
                bool rethrow = ExceptionPolicy.HandleException(ex, "GADN Custom Exception Policy");
                throw new GADNCustomException("Some Errors have occurred in the application.", "LearningSourcesDetails", "btnFirst_Click");
            }
        }

        protected void btnNew_Click(object sender, EventArgs e)
        {
            try
            {
                Response.Redirect(VirtualPathUtility.ToAbsolute("~/") + @"Pages/Administrator/EmployeeDetails.aspx", false);
            }
            catch (Exception ex)                                        
            {
                bool rethrow = ExceptionPolicy.HandleException(ex, "GADN Custom Exception Policy");
                throw new GADNCustomException("Some Errors have occurred in the application.", "LearningSourcesDetails", "btnNew_Click");
            }
        }

        #region override PageBase methods
        protected override void SavePageStateToPersistenceMedium(object pageViewState)
        {
            LosFormatter losformatter = new LosFormatter();
            StringWriter sw = new StringWriter();
            losformatter.Serialize(sw, pageViewState);
            string viewStateString = sw.ToString();
            byte[] b = Convert.FromBase64String(viewStateString);
            b = PageBase.CompressViewState(b);
            //ClientScript.RegisterHiddenField("__CUSTOMVIEWSTATE", Convert.ToBase64String(b));

            try
            {
                if (this.IsAjaxPostBack)
                {
                    ScriptManager.RegisterHiddenField(this, "__CUSTOMVIEWSTATE", Convert.ToBase64String(b));
                }
                else
                {
                    ClientScript.RegisterHiddenField("__CUSTOMVIEWSTATE", Convert.ToBase64String(b));
                }
            }
            catch
            {
                ClientScript.RegisterHiddenField("__CUSTOMVIEWSTATE", Convert.ToBase64String(b));
            }
        }

        // Deserialize view state
        protected override object LoadPageStateFromPersistenceMedium()
        {
            string custState = Request.Form["__CUSTOMVIEWSTATE"];
            byte[] b = Convert.FromBase64String(custState);
            b = PageBase.DecompressViewState(b);
            LosFormatter losformatter = new LosFormatter();
            return losformatter.Deserialize(Convert.ToBase64String(b));
        }

        private bool IsAjaxPostBack
        {
            get
            {
                if (Request.ServerVariables["HTTP_X_MICROSOFTAJAX"] != null || Request.Form["__CALLBACKID"] != null)
                    return true;
                else
                    return false;
            }
        }
        #endregion
        

    }
}


